import * as vscode from 'vscode';
import os from 'os';
import fs from 'fs';
import path from 'path';
import archiver from 'archiver';

class FiltUtils {
    context?: vscode.ExtensionContext;

    init(context: vscode.ExtensionContext) {
        this.context = context;
    }

    getFileOrDirectory(invoke: (filePath: string) => any, canSelectFiles: boolean = false, canSelectFolders: boolean = true, filters: { [name: string]: string[] } = {}) {
        const options: vscode.OpenDialogOptions = {
            canSelectFiles,
            canSelectFolders,
            filters,
            openLabel: '选择文件',
            defaultUri: vscode.Uri.file(os.homedir()),
        };
        vscode.window.showOpenDialog(options).then((data: vscode.Uri[] | undefined) => {
            if (data) {
                invoke(data[0].fsPath);
            }
        });
    }

    link(src: String, dest: String) {
        const exec = require('child_process').exec;
        switch (process.platform) {
            case 'win32':
                exec("cmd /C mklink /J \"" + dest + "\" \"" + src + "\"", () => { });
                break;
            case 'linux':
                exec("ln -s \"" + src + "\" \"" + dest + "\"", () => { });
                break;
            case 'darwin':
                exec("ln -s \"" + src + "\" \"" + dest + "\"", () => { });
                break;
        }

    }

    createJar(targetJar: string, sourceFolder: string) {
        const output = fs.createWriteStream(targetJar);
        const archive = archiver('zip', {
            zlib: { level: 0 }
        });
        archive.pipe(output);
        fs.readdirSync(sourceFolder).forEach(file => {
            let f = sourceFolder + file;
            if (fs.statSync(f).isDirectory()) {
                archive.directory(f, path.basename(f));
            } else {
                archive.file(f, { name: path.basename(f) });
            }
        });
        archive.finalize();
    }

    async  getJavaProjectsInWorkspace(): Promise<string[]> {
        const javaProjects: string[] = [];
        const workspaceFolders = vscode.workspace.workspaceFolders;
        if (!workspaceFolders) {
            return [];
        }
        for (const folder of workspaceFolders) {
            const pomXmlUri = vscode.Uri.joinPath(folder.uri, 'pom.xml');
            const gradleBuildUri = vscode.Uri.joinPath(folder.uri, 'build.gradle');
            const srcDirUri = vscode.Uri.joinPath(folder.uri,'src');
    
            const pomExists = await vscode.workspace.fs.stat(pomXmlUri).then(() => true, () => false);
            const gradleBuildExists = await vscode.workspace.fs.stat(gradleBuildUri).then(() => true, () => false);
            const srcDirExists = await vscode.workspace.fs.stat(srcDirUri).then(() => true, () => false);
    
            if ((pomExists || gradleBuildExists) && srcDirExists) {
                javaProjects.push(folder.name);
            }
        }
        return javaProjects;
    }
    
    async getJavaProjectsBySearch(): Promise<string[]> {
        const pomResults = await vscode.workspace.findFiles('**/pom.xml', '**/node_modules/**');
    
        if(pomResults.length !== 0) {
            return pomResults.map(f=>{
                let path = f.path.split("/");
                return path[path.length-2];
            });
        }
        const gradleResults = await vscode.workspace.findFiles('**/build.gradle', '**/node_modules/**');
        if(gradleResults.length !== 0) {
            return gradleResults.map(f=>{
                let path = f.path.split("/");
                return path[path.length-2];
            });
        }
        const srcDirResults = await vscode.workspace.findFiles('**/src', '**/node_modules/**');
        if(srcDirResults.length !== 0) {
            return gradleResults.map(f=>{
                let path = f.path.split("/");
                return path[path.length-2];
            });
        }
        return [];
    }
}
const filtUtils = new FiltUtils();
export default filtUtils;